package org.jeecg.modules.demo.hdPeerSupervisionLeader3.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.query.QueryRuleEnum;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.hdPeerSupervisionLeader3.entity.HdPeerSupervisionLeader3;
import org.jeecg.modules.demo.hdPeerSupervisionLeader3.service.IHdPeerSupervisionLeader3Service;
import org.jeecg.modules.demo.hdpeersupervision.entity.HdPeerSupervisionVo;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

 /**
 * @Description: 同级监督(领导人魏)
 * @Author: jeecg-boot
 * @Date:   2025-07-22
 * @Version: V1.0
 */
@Tag(name="同级监督(领导人魏)")
@RestController
@RequestMapping("/hdPeerSupervisionLeader3/hdPeerSupervisionLeader3")
@Slf4j
public class HdPeerSupervisionLeader3Controller extends JeecgController<HdPeerSupervisionLeader3, IHdPeerSupervisionLeader3Service> {
	@Autowired
	private IHdPeerSupervisionLeader3Service hdPeerSupervisionLeader3Service;
	@Autowired
	private ISysBaseAPI sysBaseAPI;
	@Autowired
	private ISysDepartService sysDepartService;
//	/**
//	 * 分页列表查询
//	 *
//	 * @param hdPeerSupervisionLeader3
//	 * @param pageNo
//	 * @param pageSize
//	 * @param req
//	 * @return
//	 */
//	//@AutoLog(value = "同级监督(领导人魏)-分页列表查询")
//	@Operation(value="同级监督(领导人魏)-分页列表查询", description="同级监督(领导人魏)-分页列表查询")
//	@GetMapping(value = "/list")
//	public Result<IPage<HdPeerSupervisionLeader3>> queryPageList(HdPeerSupervisionLeader3 hdPeerSupervisionLeader3,
//								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
//								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
//								   HttpServletRequest req) {
//        // 自定义查询规则
//        Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
//        // 自定义多选的查询规则为：LIKE_WITH_OR
//        customeRuleMap.put("project", QueryRuleEnum.LIKE_WITH_OR);
//        customeRuleMap.put("companyDepartment", QueryRuleEnum.LIKE_WITH_OR);
//        QueryWrapper<HdPeerSupervisionLeader3> queryWrapper = QueryGenerator.initQueryWrapper(hdPeerSupervisionLeader3, req.getParameterMap(),customeRuleMap);
//		Page<HdPeerSupervisionLeader3> page = new Page<HdPeerSupervisionLeader3>(pageNo, pageSize);
//		IPage<HdPeerSupervisionLeader3> pageList = hdPeerSupervisionLeader3Service.page(page, queryWrapper);
//		return Result.OK(pageList);
//	}

	 /**
	  * 分页列表查询
	  *
	  * @param hdPeerSupervisionLeader
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 //@AutoLog(value = "同级监督(领导人)-分页列表查询")
	 @Operation(summary="同级监督(领导人)-分页列表查询", description="同级监督(领导人)-分页列表查询")
	 @GetMapping(value = "/list")
	 public Result<IPage<HdPeerSupervisionLeader3>> queryPageList(HdPeerSupervisionLeader3 hdPeerSupervisionLeader,
																  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
																  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
																  HttpServletRequest req) {
		 //获取登录人的信息
		 LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 if (loginUser.getRoleCode().equals("admin")||loginUser.getRoleCode().equals("leader")) {
			 // 自定义查询规则
			 Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
			 // 自定义多选的查询规则为：LIKE_WITH_OR
			 customeRuleMap.put("project", QueryRuleEnum.LIKE_WITH_OR);
			 customeRuleMap.put("companyDepartment", QueryRuleEnum.LIKE_WITH_OR);
			 QueryWrapper<HdPeerSupervisionLeader3> queryWrapper = QueryGenerator.initQueryWrapper(hdPeerSupervisionLeader, req.getParameterMap(), customeRuleMap);
			 Page<HdPeerSupervisionLeader3> page = new Page<HdPeerSupervisionLeader3>(pageNo, pageSize);
			 IPage<HdPeerSupervisionLeader3> pageList = hdPeerSupervisionLeader3Service.page(page, queryWrapper);
			 return Result.OK(pageList);
		 }else
		 {
			 String id = loginUser.getDepartIds();
			 String departName = sysDepartService.getDepartNameById(id);
			 System.out.println("departName = " + departName);
			 // 自定义查询规则
			 Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
			 // 自定义多选的查询规则为：LIKE_WITH_OR
			 customeRuleMap.put("project", QueryRuleEnum.LIKE_WITH_OR);
			 QueryWrapper<HdPeerSupervisionLeader3> queryWrapper = QueryGenerator.initQueryWrapper(hdPeerSupervisionLeader, req.getParameterMap(),customeRuleMap);
			 queryWrapper.eq("company_department",departName);
			 Page<HdPeerSupervisionLeader3> page = new Page<HdPeerSupervisionLeader3>(pageNo, pageSize);
			 IPage<HdPeerSupervisionLeader3> pageList = hdPeerSupervisionLeader3Service.page(page, queryWrapper);
			 return Result.OK(pageList);
		 }
	 }

	/**
	 *   添加
	 *
	 * @param hdPeerSupervisionLeader3
	 * @return
	 */
	@AutoLog(value = "同级监督(领导人魏)-添加")
	@Operation(summary="同级监督(领导人魏)-添加", description="同级监督(领导人魏)-添加")
	@RequiresPermissions("hdPeerSupervisionLeader3:hd_peer_supervision_leader3:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody HdPeerSupervisionLeader3 hdPeerSupervisionLeader3) {
		hdPeerSupervisionLeader3Service.save(hdPeerSupervisionLeader3);
		return Result.OK("添加成功！");
	}

	 /**
	  *   添加
	  *
	  * @param hdPeerSupervisionLeader3
	  * @return
	  */
	 @AutoLog(value = "同级监督(领导人魏)-批量添加")
	 @Operation(summary="同级监督(领导人魏)-批量添加", description="同级监督(领导人魏)-批量添加")
	 @RequiresPermissions("hdPeerSupervisionLeader3:hd_peer_supervision_leader3:add")
	 @PostMapping(value = "/addBatch")
	 public Result<String> add(@RequestBody List<HdPeerSupervisionLeader3> hdPeerSupervisionLeader3) {
		 hdPeerSupervisionLeader3Service.saveBatch(hdPeerSupervisionLeader3);
		 return Result.OK("添加成功！");
	 }

	/**
	 *  编辑
	 *
	 * @param hdPeerSupervisionLeader3
	 * @return
	 */
	@AutoLog(value = "同级监督(领导人魏)-编辑")
	@Operation(summary="同级监督(领导人魏)-编辑", description="同级监督(领导人魏)-编辑")
	@RequiresPermissions("hdPeerSupervisionLeader3:hd_peer_supervision_leader3:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody HdPeerSupervisionLeader3 hdPeerSupervisionLeader3) {
		hdPeerSupervisionLeader3Service.updateById(hdPeerSupervisionLeader3);
		return Result.OK("编辑成功!");
	}

	 /**
	  *  编辑
	  *
	  * @param hdPeerSupervisionLeader3
	  * @return
	  */
	 @AutoLog(value = "同级监督(领导人魏)-管理员更改")
	 @Operation(summary="同级监督(领导人魏)-管理员更改", description="同级监督(领导人魏)-管理员更改")
	 @RequiresPermissions("hdPeerSupervisionLeader3:hd_peer_supervision_leader3:update")
	 @RequestMapping(value = "/update", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> update(@RequestBody HdPeerSupervisionLeader3 hdPeerSupervisionLeader3) {
		 hdPeerSupervisionLeader3Service.updateById(hdPeerSupervisionLeader3);
		 return Result.OK("编辑成功!");
	 }

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "同级监督(领导人魏)-通过id删除")
	@Operation(summary="同级监督(领导人魏)-通过id删除", description="同级监督(领导人魏)-通过id删除")
	@RequiresPermissions("hdPeerSupervisionLeader3:hd_peer_supervision_leader3:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		hdPeerSupervisionLeader3Service.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "同级监督(领导人魏)-批量删除")
	@Operation(summary="同级监督(领导人魏)-批量删除", description="同级监督(领导人魏)-批量删除")
	@RequiresPermissions("hdPeerSupervisionLeader3:hd_peer_supervision_leader3:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.hdPeerSupervisionLeader3Service.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	 /**
	  *  编辑
	  *
	  * @param hdPeerSupervisionLeader
	  * @return
	  */
	 @AutoLog(value = "同级监督(领导人)-审核")
	 @Operation(summary="同级监督(领导人)-审核", description="同级监督(领导人)-审核")
	 @RequiresPermissions("hdPeerSupervisionLeader3:hd_peer_supervision_leader3:audit")
	 @RequestMapping(value = "/audit", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> audit(@RequestBody HdPeerSupervisionLeader3 hdPeerSupervisionLeader) {
		 if (hdPeerSupervisionLeader.getFlag().equals("2")){
			 String userName = sysBaseAPI.getUserByName(hdPeerSupervisionLeader.getUpdateBy()).getUsername();
			 MessageDTO message = new MessageDTO("系统", userName,
					 "信息填写错误，请修改",
					 hdPeerSupervisionLeader.getOpinion());
			 sysBaseAPI.sendSysAnnouncement(message);
		 }
		 hdPeerSupervisionLeader3Service.updateById(hdPeerSupervisionLeader);
		 return Result.OK("审核完成");
	 }
	 /**
	  *  编辑
	  *
	  * @param hdPeerSupervisionLeader
	  * @return
	  */
	 @AutoLog(value = "同级监督(领导人)-重新上传")
	 @Operation(summary="同级监督(领导人)-重新上传", description="同级监督(领导人)-重新上传")
	 @RequiresPermissions("hdPeerSupervisionLeader3:hd_peer_supervision_leader3:reUpload")
	 @RequestMapping(value = "/reUpload", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> reUpload(@RequestBody HdPeerSupervisionLeader3 hdPeerSupervisionLeader) {
		 hdPeerSupervisionLeader3Service.updateById(hdPeerSupervisionLeader);
		 return Result.OK("重新上传!");
	 }

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "同级监督(领导人魏)-通过id查询")
	@Operation(summary="同级监督(领导人魏)-通过id查询", description="同级监督(领导人魏)-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<HdPeerSupervisionLeader3> queryById(@RequestParam(name="id",required=true) String id) {
		HdPeerSupervisionLeader3 hdPeerSupervisionLeader3 = hdPeerSupervisionLeader3Service.getById(id);
		if(hdPeerSupervisionLeader3==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(hdPeerSupervisionLeader3);
	}


	 @Operation(summary="同级监督(领导人)-导出excel合并单元格", description="同级监督(领导人)-导出excel合并单元格")
	 @GetMapping(value = "/exportXlsMergeCells")
	 public Result<byte[]> exportXlsMergeCells(HttpServletRequest request, HdPeerSupervisionLeader3 hdPeerSupervisionLeader3) throws IOException {
		 // Step.1 组装查询条件
		 QueryWrapper<HdPeerSupervisionLeader3> queryWrapper =new QueryWrapper<>();
		 // 过滤选中数据
		 String selections = request.getParameter("selections");
//		 System.out.println("selections = " + selections);
		 String department = request.getParameter("department");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 System.out.println("selectionList = " + selectionList);
			 queryWrapper.in("id",selectionList);
		 }  else if (oConvertUtils.isNotEmpty(department)) {
			 List<String> departmentList = Arrays.asList(department.split(","));
			 queryWrapper.in("company_department",departmentList);
		 }
		 // Step.2 获取导出数据
		 List<HdPeerSupervisionLeader3> exportList = hdPeerSupervisionLeader3Service.list(queryWrapper);
		 // 2. 生成Excel字节数组
		 byte[] excelBytes = hdPeerSupervisionLeader3Service.generateExcelBytes(exportList);
		 return Result.OK(excelBytes);

	 }

	 @Operation(summary = "同级监督(领导人魏)-查询所有部门的填报率", description = "同级监督(领导人魏)-查询所有部门的填报率")
	 @GetMapping(value = "/queryAllDepartmentFillRate")
	 public Result<Map<String, HdPeerSupervisionVo>> queryAllDepartmentFillRate() {
		 Map<String, HdPeerSupervisionVo> result = new HashMap<>();
		 Long total = 0L;
		 Long complete = 0L;
		 double fillRate = 0.0;
		 List<SysDepart> departList = sysDepartService.list();
		 for (int i = 0; i < departList.size(); i++) {
			 String departName = departList.get(i).getDepartName();
//            System.out.println("departName = " + departName);
			 // 查询该部门的总记录数
			 Long DepartTotal = hdPeerSupervisionLeader3Service.count(new QueryWrapper<HdPeerSupervisionLeader3>()
					 .eq("company_department", departName));
//            System.out.println("DepartTotal = " + DepartTotal);
			 // 如果没有记录，跳过该部门
			 if (DepartTotal == 0L) {
				 continue;
			 }
			 HdPeerSupervisionVo hdPeerSupervisionVo = new HdPeerSupervisionVo();
			 total = hdPeerSupervisionLeader3Service.count(new QueryWrapper<HdPeerSupervisionLeader3>().eq("company_department", departList.get(i).getDepartName()));
			 complete = hdPeerSupervisionLeader3Service.count(new QueryWrapper<HdPeerSupervisionLeader3>().eq("company_department", departList.get(i).getDepartName()).in("flag", "1", "2", "3"));
			 Long notTotal = hdPeerSupervisionLeader3Service.count(new QueryWrapper<HdPeerSupervisionLeader3>().eq("company_department", departList.get(i).getDepartName())
					 .in("flag", "0"));
			 Long pendingApprovalTotal = hdPeerSupervisionLeader3Service.count(new QueryWrapper<HdPeerSupervisionLeader3>().eq("company_department", departList.get(i).getDepartName())
					 .in("flag", "1"));
			 Long rejectTotal = hdPeerSupervisionLeader3Service.count(new QueryWrapper<HdPeerSupervisionLeader3>().eq("company_department", departList.get(i).getDepartName())
					 .in("flag", "2"));
			 Long agreeTotal = hdPeerSupervisionLeader3Service.count(new QueryWrapper<HdPeerSupervisionLeader3>().eq("company_department", departList.get(i).getDepartName())
					 .in("flag", "3"));
			 hdPeerSupervisionVo.setNotTotal(notTotal);
			 hdPeerSupervisionVo.setPendingApprovalTotal(pendingApprovalTotal);
			 hdPeerSupervisionVo.setRejectTotal(rejectTotal);
			 hdPeerSupervisionVo.setAgreeTotal(agreeTotal);
			 if (total != 0L) {
				 fillRate = (double) complete / total;
				 //fillRate保留小数点后两位
				 fillRate=new BigDecimal(fillRate).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
				 hdPeerSupervisionVo.setFillRate(fillRate);
			 }
			 result.put(departList.get(i).getDepartName(), hdPeerSupervisionVo);
		 }
		 return Result.OK(result);
	 }


    /**
    * 导出excel
    *
    * @param request
    * @param hdPeerSupervisionLeader3
    */
    @RequiresPermissions("hdPeerSupervisionLeader3:hd_peer_supervision_leader3:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HdPeerSupervisionLeader3 hdPeerSupervisionLeader3) {
        return super.exportXls(request, hdPeerSupervisionLeader3, HdPeerSupervisionLeader3.class, "同级监督(领导人魏)");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("hdPeerSupervisionLeader3:hd_peer_supervision_leader3:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HdPeerSupervisionLeader3.class);
    }

}
